package zk.dwj.cn;

import org.apache.zookeeper.*;

/**
 * Created by Administrator on 2017/11/13 0013.
 */
public class CreateNodeASync implements Watcher{

    private static ZooKeeper zooKeeper;

    public void process(WatchedEvent watchedEvent) {
        System.out.print("收到事件：" + watchedEvent);
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            doSomething();
        }
    }

    private void doSomething() {//异步创建
        System.out.println("do some thing");

        zooKeeper.create("/node_2","123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new IStringCallback(), "创建");
            //System.out.println("return path : " + path);

    }


    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("192.168.110.134:2181", 5000, new CreateNodeASync());
            System.out.println(zooKeeper.getState());
            Thread.sleep(Integer.MAX_VALUE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    static class IStringCallback implements AsyncCallback.StringCallback{

        public void processResult(int rc, String path, Object ctx, String realPath) {
            StringBuilder sb = new StringBuilder();
            sb.append("rc="+rc).append("\n");
            sb.append("path="+path).append("\n");
            sb.append("ctx="+ctx).append("\n");
            sb.append("realPath="+realPath).append("\n");
            System.out.println(sb.toString());

            /*rc=0
            path=/node_2
            ctx=创建
            realPath=/node_2*/

        }
    }
}
